package com.example.goodsserver.manager;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.goodsserver.entity.GoodsInfo;
import com.example.goodsserver.mapper.GoodsMapper;
import com.example.goodsserver.params.PageGoodsParams;
import com.example.goodsserver.vo.GoodsInfoVO;
import com.example.userserver.utils.BeanCopyUtils;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

@Service
public class GoodsManager {
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private GoodsCacheManager goodsCacheManager;
    public void insertGoods(GoodsInfo goodsInfo){
        goodsMapper.insert(goodsInfo);
    }

    public void deleteGoods(String id){
        goodsMapper.deleteById(id);
    }

    public void updateGoods(GoodsInfo goodsInfo){
        goodsMapper.updateById(goodsInfo);
    }
    public List<GoodsInfoVO> listGoods(PageGoodsParams pageGoodsParams){
        return goodsMapper.pageGoods(pageGoodsParams);
    }

    public GoodsInfoVO getGoods(String id){
        // 查商品详情缓存
        GoodsInfoVO goodsInfoVOCache = goodsCacheManager.getGoodsInfoCache(id);
        // 有缓存直接返回
        if(ObjectUtil.isNotEmpty(goodsInfoVOCache)){
            return goodsInfoVOCache;
        }else{ // 无缓存 查DB 保存回缓存
           return selectDBSaveCache(id);
        }
    }

    // 查DB 保存回缓存
    public GoodsInfoVO selectDBSaveCache(String id){
        GoodsInfoVO goodsInfoVODB = goodsMapper.getGoodsById(id);
        goodsCacheManager.saveGoodsInfoVOCache(goodsInfoVODB.getId(), goodsInfoVODB);
        return goodsInfoVODB;
    }

    public GoodsInfo getGoodsInfo(String id){
        return goodsMapper.selectById(id);
    }

    public List<GoodsInfoVO> pageGoodsPersonal(QueryWrapper queryWrapper) {
        return goodsMapper.selectList(queryWrapper);
    }
}
